package be.dch.typeditor.parser;

import java.awt.Color;
import java.util.HashMap;
import java.util.Map;

import be.dch.typeditor.domain.GarminIcon;
import be.dch.util.ArrayUtils;

public final class GarminIconParser {

    private final transient Map<Color, Character> colorMap = new HashMap<Color, Character>();
    private final transient GarminIcon garminIcon;

    public static String[] toStringArray(final String[] response, final GarminIcon icon) {
	String[] result = new String[response.length];
	System.arraycopy(response, 0, result, 0, response.length);
	final GarminIconParser parser = new GarminIconParser(icon);
	result = (String[]) ArrayUtils.add(result, parser.getColorSchema());
	result = (String[]) ArrayUtils.add(result, parser.getPattern());
	return result;
    }

    private GarminIconParser(final GarminIcon icon) {
	this.garminIcon = icon;
	this.loadColorMap(icon);
    }

    private void loadColorMap(final GarminIcon icon) {
	final Color[] colors = icon.getColors();
	for (final Color color : colors) {
	    final int colorNextChar = (this.colorMap.size() + 17);
	    final Character colorChar = new Character((char) colorNextChar);
	    this.colorMap.put(color, colorChar);
	}
    }

    private String[] getColorSchema() {
	String[] imageColors = new String[] {};
	for (final Color color : this.colorMap.keySet()) {
	    final StringBuffer colorLine = new StringBuffer();
	    colorLine.append(this.colorMap.get(color).toString());
	    colorLine.append(" c ");
	    if (color == this.garminIcon.getTransparent()) {
		colorLine.append("none");
	    } else {
		colorLine.append('#');
		colorLine.append(Integer.toHexString(color.getRGB() & 0x00ffffff));
	    }
	    imageColors = (String[]) ArrayUtils.add(imageColors, colorLine);
	}
	return imageColors;
    }

    /**
     * Gets string representation of the image
     * 
     * @return
     */
    private String[] getPattern() {
	final Color[] colors = this.garminIcon.getColors();
	String[] rowArray = new String[] {};
	final StringBuffer row = new StringBuffer();
	for (int i = 0; i < colors.length; i++) {
	    row.append(this.colorMap.get(colors[i]));
	    if ((i % this.garminIcon.getDimension().width) == 0) {
		rowArray = (String[]) ArrayUtils.add(rowArray, row.toString());
		// FIXME append
	    }
	}
	return rowArray;
    }

}
